package com.example.capsule_chat0322.adapter;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;


import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.OneToOneChatActivity;
import com.example.capsule_chat0322.bean.GlobalRoomBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalChatRoomMap;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.interfaces.FriendItemOnClickInterface;
import com.example.capsule_chat0322.request.UserInfoRequest;

import java.util.Base64;
import java.util.List;

/**
 * @Author zhuzhiming
 * @Date 2022/5/1 21:21
 */
public class FriendListAdapter extends RecyclerView.Adapter<FriendListAdapter.ViewHold> implements View.OnClickListener {

    public List<UserInfoBean> friendBeanList;
    private FriendItemOnClickInterface friendItemOnClickInterface;
    private RecyclerView rvParent;

    public void setFriendItemOnClickListener(FriendItemOnClickInterface friendItemOnClickInterface) {
        this.friendItemOnClickInterface = friendItemOnClickInterface;
    }


    static class ViewHold extends RecyclerView.ViewHolder {

        LinearLayout friend_item;
        TextView friend_info;
        ImageView friend_avatar;
        TextView message_count;

        public ViewHold(@NonNull View itemView) {
            super(itemView);
            friend_item = itemView.findViewById(R.id.friend_item);
            message_count = itemView.findViewById(R.id.message_count);
            friend_info = itemView.findViewById(R.id.friend_info);
            friend_avatar = itemView.findViewById(R.id.friend_avatar);
        }
    }


    public FriendListAdapter(List<UserInfoBean> friendBeanList) {
        this.friendBeanList = friendBeanList;
    }

    @NonNull
    @Override
    public ViewHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        rvParent = (RecyclerView) parent;
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.friend_item, parent, false);
        view.setOnClickListener(this);
        return new FriendListAdapter.ViewHold(view);
    }

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull ViewHold holder, int position) {

        UserInfoBean friendBean = friendBeanList.get(position);
        GlobalAssistMap.putObject(friendBean.getId() + "position", position + "");

        holder.friend_item.setVisibility(View.VISIBLE);
        String onlineStatus = friendBean.getOnlineStatus() == 0 ? "离线" : "在线";
        String nickname = friendBean.getNickname().length() > 12 ? friendBean.getNickname().substring(0, 12) : friendBean.getNickname();
        holder.friend_info.setText(nickname + "(" + onlineStatus + ")" + "\n"
                + friendBean.getLastMessage());


        int count = friendBean.getNewMessageCount();
        if (count == 0) {
            holder.message_count.setVisibility(View.GONE);
        } else {
            holder.message_count.setVisibility(View.VISIBLE);
            String messageCount = "";
            if (count > 99) {
                messageCount = "99+";
            } else if (count == -1) {
                messageCount = "1";
            } else {
                messageCount = String.valueOf(count);
            }
            holder.message_count.setText(messageCount);
        }

        String avatarPath = friendBean.getAvatarUrl();
        if (avatarPath.contains("/")) {
            LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
            String cacheKey = avatarPath.substring(avatarPath.lastIndexOf("/") + 1);
            final Bitmap[] bitmap = {(Bitmap) lruCache.get(cacheKey)};
            if (bitmap[0] == null) {
                bitmap[0] = BitmapFactory.decodeFile(cacheKey);
                if (bitmap[0] == null) {
                    UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                        @Override
                        public boolean handleMessage(@NonNull Message message) {
                            bitmap[0] = BitmapFactory.decodeFile(Constant.IMAGE_PATH + avatarPath.substring(avatarPath.lastIndexOf("/") + 1));
                            lruCache.put(cacheKey, bitmap[0]);
                            holder.friend_avatar.setImageBitmap(bitmap[0]);
                            return true;
                        }
                    }), friendBean.getAvatarServerPath());
                } else {
                    holder.friend_avatar.setImageBitmap(bitmap[0]);
                }
            } else {
                holder.friend_avatar.setImageBitmap(bitmap[0]);
            }
        } else {
            holder.friend_avatar.setImageResource(Integer.parseInt(avatarPath));
        }
    }

    @Override
    public int getItemCount() {
        return friendBeanList.size();
    }


    @Override
    public void onClick(View view) {
        //根据RecyclerView获得当前View的位置
        int position = rvParent.getChildAdapterPosition(view);
        //程序执行到此，会去执行具体实现的onItemClick()方法
        if (friendItemOnClickInterface != null) {
            friendItemOnClickInterface.onItemClick(rvParent, view, position, friendBeanList.get(position));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("SetTextI18n")
    public void updateFriendListView(View view, MessageBean messageBean, String content) {


        if (messageBean.getMsgType() == 9) {
            updateLastMessageView(view, messageBean.getSenderId(), String.valueOf(messageBean.getStatus()), true, true);
            return;
        }

        String userId = messageBean.getSenderId();

        updateLastMessageView(view, userId, content, false, true);

        String roomName = Integer.parseInt(userId) + Integer.parseInt(GlobalAssistMap.getObject("userId").toString()) + "chatroom";

        GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(roomName);

        if (globalRoomBean == null) {
            return;
        }

        List<Msg> msgList = globalRoomBean.getMsgList();

        Msg receiveMsg = null;

        if (messageBean.getMsgType() == Msg.WORD_TYPE) {
            receiveMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, messageBean.getContent(), Msg.TYPE_RECEIVE, messageBean.getSenderAvatarPath(), true);
            receiveMsg.setId(messageBean.getMsgId());
        } else {

            if (messageBean.getMsgType() == 1) {

                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(messageBean.getFileName());
                // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(finalMessageBean.getFileName());
                if (bitmap == null) {
                    byte[] by = Base64.getDecoder().decode(messageBean.getContent());
                    bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                    if (bitmap != null) {
                        lruCache.put(messageBean.getFileName(), bitmap);
                        // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                    }
                    by = null;
                }
                receiveMsg = new Msg(messageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, messageBean.getFileName(), messageBean.getRoomName(), messageBean.getSenderAvatarPath(), null, true);
                receiveMsg.setId(messageBean.getMsgId());
            } else if (messageBean.getMsgType() == 2) {
                receiveMsg = new Msg(messageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.FILE_SERVER_PATH + messageBean.getFileName(), messageBean.getRoomName(), messageBean.getSenderAvatarPath(), messageBean.getFileName() + " " + messageBean.getFileSize(), true);
                receiveMsg.setId(messageBean.getMsgId());
            } else if (messageBean.getMsgType() == 3) {

                String cacheKey = messageBean.getFileName();
                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                if (bitmap == null) {
                    byte[] by = Base64.getDecoder().decode(messageBean.getContent());
                    bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                    if (bitmap != null) {
                        lruCache.put(messageBean.getFileName(), bitmap);
                        //GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                    }
                    by = null;
                }

                receiveMsg = new Msg(messageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.VIDEO_SERVER_PATH + messageBean.getFileName(), messageBean.getRoomName(), messageBean.getSenderAvatarPath(), ".mp4 ", true);
                receiveMsg.setId(messageBean.getMsgId());
            } else if (messageBean.getMsgType() == 8) {

                int msgId = messageBean.getMsg().getId();
                for (int i = 0; i < msgList.size(); i++) {
                    if (msgList.get(i).getId() == msgId) {
                        Msg newMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, messageBean.getSenderAvatarPath(), true);
                        msgList.remove(i);
                        msgList.add(i, newMsg);
                        break;
                    }
                }

                String str = "" + "|" + messageBean.getSenderName();
                Msg remindMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "", true);
                msgList.add(remindMsg);
                return;
            }
        }

        msgList.add(receiveMsg);

    }


    @SuppressLint("SetTextI18n")
    public void updateLastMessageView(View view, String userId, String content, boolean needToUpdateStatus, boolean isNew) {

        LinearLayout friend_item;
        TextView friend_info;
        TextView message_count;

        friend_item = view.findViewById(R.id.friend_item);
        message_count = view.findViewById(R.id.message_count);
        friend_info = view.findViewById(R.id.friend_info);

        if (needToUpdateStatus) {
            String roomName = Integer.parseInt(userId) + Integer.parseInt(GlobalAssistMap.getObject("userId").toString()) + "chatroom";
            GlobalRoomBean roomInfo = GlobalChatRoomMap.getRoomInfo(roomName);
            if (roomInfo != null) {
                OneToOneChatActivity activity = (OneToOneChatActivity) roomInfo.getActivity();
                activity.runOnUiThread(() -> {
                    activity.updateFriendStatus(Integer.parseInt(content));
                });

            }
        }

        String position = (String) GlobalAssistMap.getObject(userId + "position");
        if (position == null) {
            return;
        }


        friend_item.setVisibility(View.VISIBLE);
        UserInfoBean userInfoBean = friendBeanList.get(Integer.parseInt(position));
        if (needToUpdateStatus) {
            userInfoBean.setOnlineStatus(Integer.parseInt(content));
            String onlineStatus = userInfoBean.getOnlineStatus() == 0 ? "离线" : "在线";
            try {
                String currStr = friend_info.getText().toString();
                String nickName = currStr.substring(0, currStr.indexOf("("));
                String curContent = currStr.substring(currStr.indexOf(")") + 1);
                friend_info.setText(nickName + "(" + onlineStatus + ")" + curContent);

            } catch (Exception e) {
                Log.e("errorText", e.toString());
                return;
            }
        }


        String unSignMessageCount = message_count.getText().toString();
        int count = 0;
        String countStr = "";
        if (unSignMessageCount.equals("") && isNew) {
            countStr = "1";
        } else if (!unSignMessageCount.equals("")) {
            count = Integer.parseInt(unSignMessageCount);
            if (count == 99) {
                countStr = "99+";
            } else {
                countStr = String.valueOf(count + 1);
            }
        }


        String finalCountStr = countStr;
        message_count.post(new Runnable() {
            @Override
            public void run() {
                if (!isNew) {
                    message_count.setVisibility(View.GONE);
                } else {
                    message_count.setVisibility(View.VISIBLE);
                    message_count.setText(finalCountStr);
                }

            }
        });


        String onlineStatus = userInfoBean.getOnlineStatus() == 0 ? "离线" : "在线";
        try {
            String nickname = userInfoBean.getNickname().length() > 12 ? userInfoBean.getNickname().substring(0, 12) : userInfoBean.getNickname();
            friend_info.setText(nickname + "(" + onlineStatus + ")" + "\n" + content);
        } catch (Exception e) {
            Log.e("errorText", e.toString());
        }
    }


    public void deleteUnSignDot(View view) {

        TextView message_count;
        message_count = view.findViewById(R.id.message_count);

        message_count.setText("");
        message_count.setVisibility(View.GONE);

    }

}
